<script setup lang="tsx">
defineOptions({ name: "UserInfo" });
import pwdFrom from "./pwd.vue";
import dialogFrom from "./form.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import Iphone from "@iconify-icons/ep/iphone";
import { addDialog } from "@/components/ReDialog";
import MessageIcon from "@iconify-icons/ep/message";
import { FileType } from "@/store/types";
import { updateInfo, updatePassword, updatePhoneOrEmail } from "@/api/user";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import ReCropperPreview from "@/components/ReCropperPreview";
import { createFormData, deviceDetection, isAllEmpty } from "@pureadmin/utils";
import { upload } from "@/api/upload";
const { t } = useI18n();
const uploadRef = ref();
const cropRef = ref();
const isShow = ref(false);
const imgSrc = ref("");
const cropperBlob = ref(); // 裁剪后的图片
const userInfos = reactive({
  id: 0,
  sex: 0,
  avatar: "",
  userName: "",
  nickName: "",
  email: "",
  phone: "",
  description: ""
});
const userStore = useUserStoreHook();
userStore.getUserInfo().then(res => {
  Object.assign(userInfos, res);
});
const onChange = uploadFile => {
  const reader = new FileReader();
  reader.onload = e => {
    imgSrc.value = e.target.result as string;
    isShow.value = true;
  };
  reader.readAsDataURL(uploadFile.raw);
};
const onCropper = ({ blob }) => {
  cropperBlob.value = blob;
};
/** 关闭裁剪图片 */
const handleClose = () => {
  cropRef.value.hidePopover();
  uploadRef.value.clearFiles();
  isShow.value = false;
};
/** 确认上传头像 */
const handleSubmitImage = () => {
  const formData = createFormData({
    file: [{ raw: cropperBlob.value }]
  });
  upload(formData).then(async (res: FileType) => {
    userStore.SET_AVATAR(res.url);
    Object.assign(userInfos, { avatar: res.url });
    handleClose();
  });
};
function _addDialog(type: number) {
  addDialog({
    title: type == 1 ? "修改邮箱" : "修改手机号",
    center: true,
    width: "500px",
    closeOnClickModal: false,
    contentRenderer: () => h(dialogFrom),
    props: { formInline: { type } },
    beforeSure: async (done, { options }) => {
      const from = options.props.formInline;
      if (!from.value) {
        return type == 2
          ? message(t("login.purePhoneCorrectReg"), {
              type: "error"
            })
          : message(t("login.pureEmailCorrectReg"), {
              type: "error"
            });
      }
      if (!from.code)
        return message(t("login.pureVerifyCodeReg"), {
          type: "error"
        });
      await updatePhoneOrEmail(from);
      done();
    }
  });
}
const editPwd = reactive({
  oldPwd: "",
  newPwd: "",
  newPwd2: ""
});
const curScore = ref();
watch(
  () => editPwd.newPwd,
  val => {
    curScore.value = isAllEmpty(val) ? -1 : zxcvbn(val).score;
  }
);
function editPassword() {
  const pwdForm = ref();
  addDialog({
    title: t("buttons.pureModifyPassword"),
    width: "30%",
    center: true,
    draggable: true,
    closeOnClickModal: false,
    fullscreen: deviceDetection(),
    contentRenderer: () => h(pwdFrom, { ref: pwdForm }),
    beforeSure: async done => {
      const FormRef = pwdForm.value.getRef();
      FormRef.validate(async valid => {
        if (valid) {
          await updatePassword(editPwd);
          done();
        }
      });
    }
  });
}
async function saveUserInfo() {
  await updateInfo({
    id: userInfos.id,
    nickName: userInfos.nickName,
    sex: userInfos.sex,
    description: userInfos.description
  });
}
</script>

<template>
  <div>
    <el-row :gutter="20">
      <el-col :sm="12" :xs="24" :lg="10" class="mb-4">
        <el-card>
          <div class="text-center">
            <el-avatar :size="100" :src="userInfos.avatar" />
            <el-upload
              ref="uploadRef"
              accept="image/*"
              action="#"
              :limit="1"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="onChange"
            >
              <el-button plain class="mt-1" size="small"
                >{{ $t("user.editAvatar") }}
              </el-button></el-upload
            >
          </div>
          <el-divider content-position="center">{{
            $t("text.pureInfoBind")
          }}</el-divider>
          <el-form label-width="80px">
            <el-form-item :label="$t('user.phone') + ':'">
              <div class="flex justify-between w-full">
                <span>{{ userInfos.phone }}</span>
                <el-button
                  size="small"
                  type="info"
                  :icon="useRenderIcon(Iphone)"
                  @click="_addDialog(2)"
                  >{{ $t("buttons.pureModifyPhone") }}</el-button
                >
              </div>
            </el-form-item>
            <el-form-item :label="$t('user.email') + ':'">
              <div class="flex justify-between w-full">
                <span>{{ userInfos.email }}</span>
                <el-button
                  size="small"
                  type="info"
                  :icon="useRenderIcon(MessageIcon)"
                  @click="_addDialog(2)"
                  >{{ $t("buttons.pureModifyEmail") }}</el-button
                >
              </div>
            </el-form-item>
            <el-form-item label-width="0">
              <el-button
                type="warning"
                plain
                class="w-full"
                @click="editPassword"
                >{{ $t("buttons.pureModifyPassword") }}</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :sm="12" :xs="24" :lg="14">
        <el-card>
          <el-divider content-position="center">{{
            $t("text.pureUserIfo")
          }}</el-divider>
          <el-form :model="userInfos" label-width="90px">
            <el-form-item :label="$t('user.userName') + ':'">{{
              userInfos.userName
            }}</el-form-item>
            <el-form-item :label="$t('user.nickName') + ':'">
              <el-input
                v-model="userInfos.nickName"
                :placeholder="$t('user.nickNamePlaceholder')"
              />
            </el-form-item>
            <el-form-item :label="$t('user.sex') + ':'">
              <el-radio-group v-model="userInfos.sex">
                <el-radio label="男" :value="1" />
                <el-radio label="女" :value="0" />
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('user.description') + ':'">
              <el-input
                v-model="userInfos.description"
                type="textarea"
                :rows="3"
                :placeholder="$t('user.descriptionPlaceholder')"
              />
            </el-form-item>
            <el-form-item label-width="0">
              <el-button
                type="success"
                class="w-full"
                plain
                @click="saveUserInfo"
                >{{ $t("buttons.pureSave") }}</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="isShow"
      width="500px"
      center
      :title="$t('user.editAvatar')"
      destroy-on-close
      :closeOnClickModal="false"
      :before-close="handleClose"
      :fullscreen="deviceDetection()"
    >
      <ReCropperPreview ref="cropRef" :imgSrc="imgSrc" @cropper="onCropper" />
      <template #footer>
        <div class="dialog-footer">
          <el-button bg text @click="handleClose">{{
            $t("buttons.pureCancel")
          }}</el-button>
          <el-button bg text type="primary" @click="handleSubmitImage">
            {{ $t("login.pureDefinite") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
